import _ from "lodash"
import qs from "qs";
import dayjs from "dayjs";
import duration from 'dayjs/plugin/duration';
import { tbExternalLinkList } from "../api/tbExternalLink";
import { hideLoading, showLoading } from "./loading";
dayjs.extend(duration);
export const getOmitBy = (obj) => {
    if (_.isArray(obj)) {
        return obj
    }
    return _.omitBy(obj, (value) => value === "" || value === null || value === undefined);
}
export const toPage = (path) => {
    if (path.includes("##")) {
        const [linkType, linkSubType] = path.split("##")
        showLoading('查询中...')
        tbExternalLinkList({ linkType, linkSubType }).then((res) => {
            hideLoading()
            if (res.data && res.data.length > 0) {
                let linkUrl = res.data[0].linkUrl
                if (linkUrl && linkUrl.includes('@@')) {
                    const [appid, path] = linkUrl.split('@@')
                    toMiniProgram(appid, path)
                } else {
                    uni.navigateTo({
                        url: `/pages/share/qrcode?link=${res.data[0].linkUrl}&qrcode=${res.data[0].linkQrCode}`
                    })
                }
            }
        })
        return;
    }
    let { link } = getUrlParams(path)
    if (link && link.includes('@@')) {
        const [appid, path] = link.split('@@')
        toMiniProgram(appid, path)
        return;
    }
    uni.navigateTo({
        url: path
    })
}

/**
 * 对象里面的字符串小写驼峰转小写下划线
**/
export const snakeCaseIsObject = (obj) => {
    let map = {}
    for (let key in obj) {
        map[_.snakeCase(key)] = obj[key];
    }
    return map
}

export const getParentMap = (list, name, value) => {
    for (let i in list) {
        if (list[i][name] === value) {
            return [list[i]]
        }
        if (list[i].children) {
            let node = getParentMap(list[i].children, name, value);
            if (node !== undefined) {
                return node.concat(list[i])
            }
        }
    }
}
export const previewImage = (urls, index = 0) => {
    let fileUrls = [].concat(urls).map(item => `${process.env.VUE_APP_FILE_URL}${item}`)
    uni.previewImage({
        current: index,
        urls: fileUrls
    })
}

export const getFilePath = (path) => {
    if (path) {
        if (path.startsWith("http") || path.startsWith("https")) {
            return path
        }
        return `${path}`
    }
}
export const navigateBack = (params) => {
    const pages = getCurrentPages()
    if (pages.length === 1) {
        if (typeof params === 'number') {
            history.go(-params)
        } else {
            history.back()
        }
    } else {
        uni.navigateBack()
    }
}

/**
 * 获取 url 参数
 * @param {string} url
 */
export const getUrlParams = (url) => {
    const index = url.indexOf('?');
    if (index === -1) return {};
    const params = url.slice(index + 1);
    return qs.parse(params);
}
/**
 * 根据两点的经纬度获取距离
 * @param {*} lat1 纬度1
 * @param {*} lng1 经度1
 * @param {*} lat2 纬度2
 * @param {*} lng2 经度2
 **/
export const getDistance = (lat1, lng1, lat2, lng2) => {
    let EARTH_RADIUS = 6378.137; // 地球半径
    let radLat1 = lat1 * Math.PI / 180.0; //lat1 * Math.PI / 180.0=>弧度计算
    let radLat2 = lat2 * Math.PI / 180.0;
    let a = radLat1 - radLat2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) *
        Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; // 输出为公里
    return {
        m: Number((s * 1000).toFixed(2)),
        km: Number(s.toFixed(2))
    }
}
const validateNull = (val) => {
    if (typeof val === 'boolean') {
        return false
    }
    if (typeof val === 'number') {
        return false
    }
    if (val instanceof Array) {
        if (val.length === 0) return true
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}') return true
    } else {
        return val === 'null' || val == null || val === 'undefined' || val === undefined || val === '';

    }
    return false
}

/**
 * 打开高德或百度地图
 * @param {*} latitude
 * @param {*} longitude
 * @param {*} name  导航目的地名称
 * @param {*} type 1 百度地图 2 高德地图
 */
export const navToMap = (latitude = 0, longitude = 0, name = '目的地', type = 1) => {
    let url
    let lat, long
    const u = navigator.userAgent
    //判断ios
    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    //判断Android
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
    if (type === 1) {
        //百度地图 把获取到的非百度坐标转为百度坐标
        lat = latitude
        long = longitude
    } else if (type === 2) {
        //高德地图 把获取到的非GCJ-02坐标转为GCJ-02(火星坐标)
        lat = latitude
        long = longitude
    }
    if (isAndroid) {
        switch (type) {
            case 1: //百度地图
                url = `http://api.map.baidu.com/marker?location=${lat},${long}&title=${name}&content=${name}&output=html`
                break
            case 2: //高德地图
                url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${lat}&lon=${long}&dev=0`
                break
            default:
                break
        }
    } else if (isIOS) {
        switch (type) {
            case 1: //百度地图
                url = `http://api.map.baidu.com/marker?location=${lat},${long}&title=${name}&content=${name}&output=html`
                break
            case 2: //高德地图
                url = `http://uri.amap.com/marker?position=${long},${lat}&name=${name}&src=mypage&coordinate=gaode&callnative=00`
                break
            default:
                break
        }
    }
    if (!validateNull(url)) {
        window.location.href = url
    }
}
export const putVideoAndImage = (html) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const videos = doc.getElementsByTagName('video');
    const images = doc.getElementsByTagName('img');
    const processElements = (elements) => {
        for (let element of elements) {
            const width = parseInt(element.style.width);
            if (!isNaN(width) && width > 300 || isNaN(width)) {
                element.style.width = '100%';
            }
        }
    };

    processElements(videos);
    processElements(images);

    return doc.body.innerHTML;
}



export const toMiniProgram = (appId, path) => {
    jWeixin.miniProgram.postMessage({
        data: {
            appId: appId,  //小程序appid
            path: path,  //小程序跳转路径
            action: 'navigateToMiniProgram',  //固定值，不要改动
        }
    })
    jWeixin.miniProgram.navigateBack({ delta: 1 })
}
